﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public class SqlHelper
    {
        private readonly string connStr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;

        public DataTable ExecuteDataTable(string sql, params SqlParameter[] parameter)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (parameter != null)
                    {
                        cmd.Parameters.AddRange(parameter);
                    }
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable table = new DataTable();
                    adapter.Fill(table);
                    return table;
                }
            }
        }

        public object ExecuteScalar(string sql, params SqlParameter[] parameter)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    cmd.Parameters.AddRange(parameter);
                    return cmd.ExecuteScalar();
                }
            }
        }

        public int ExecuteNonQuery(string sql, params SqlParameter[] parameter)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = sql;
                    if (parameter != null)
                    {
                        cmd.Parameters.AddRange(parameter);
                    }
                    return cmd.ExecuteNonQuery();
                }
            }
        }
    }
}
